package com.fingard.dsp.bank.directbank.boc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

public class BOC01Statement extends BOC01Base implements IStatement {

    private String receiptSaveToMainDir = "";

    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpPosRespHeader = getPosStatement(p_reqQrySttm, retAts);
        String tmpPosTotalNum = retAts.totalNum;
        if ("".equals(tmpPosTotalNum)) {
            tmpPosTotalNum = "0";
        }
        String[] tmpRespHeader = getStatement(p_reqQrySttm, retAts);
        String tmpTotalNum = retAts.totalNum;
        if ("".equals(tmpTotalNum)) {
            tmpTotalNum = "0";
        }
        if ("-1".equals(tmpRespHeader[0]) && "-1".equals(tmpPosRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("POS对账单获取失败,原因:" + tmpPosRespHeader[1] + ",对账服务对账单获取失败,原因:" + tmpRespHeader[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = tmpRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpTotalNum) + Integer.parseInt(tmpPosTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }

    /**
     * 参考文档：华润对账文件格式.word
     *
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */
    public String[] getPosStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;
        try {
            StringBuilder sbFileContent = new StringBuilder();
            String downFileName = "ZHHR" + p_reqQrySttm.busDate + ".TXT";
            FtpSet ftpSet = bankFront.getFtpSet("statement");
            WriteBankLogLn2("中国银行POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            WriteBankLogLn2("中国银行POS对账单保存本地路径:" + localFilePath);

            FtpReceiver ftpReceiver = null;
            String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
            WriteBankLogLn("中国银行POS对账单获取类型" + posRecRequestType);
            if ("ftp".equals(posRecRequestType.toLowerCase())) {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
            } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, localFilePath);
            }
            if (ftpReceiver.isCompleted) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset()));
                WriteBankLogLn2("华润银行无卡收单POS对账单响应数据:\r\n" + sbFileContent.toString());
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "中国银行POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
            }

            String tmpStrRet = sbFileContent.toString();
            WriteBankLogLn2("读取本地对账文件内容数据:\r\n" + tmpStrRet);
            if (StringHelper.hasAnyChar(tmpStrRet)) {
                tmpRespCode = "0";
                /**
                 * 1、终端号|2、交易日期|3、交易时间|4、交易金额|5、批次号|6、流水号|7、对方账号|8、对方户名|9、交易结果|10、对账单类型|11、参考号
                 * 48xx2699|20190726|103855|.01|130726|889901|62170xxxxxxxxx1631||交易成功|借|920760012909|
                 * 48xx2699|20190726|104106|.01|130726|889901|62170xxxxxxxxx1631||交易成功|借|920725010676|
                 */
                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null) {
                        break;
                    }
                    if ("".equals(eachline)) {
                        continue;
                    }
                    String[] detailNodes = eachline.split("\\|");
                    if (detailNodes.length >= 11) {
                        if (p_reqQrySttm.actNum.equals(detailNodes[6].trim())) {
                            totalNum++;
                            isContinue = true;
                            RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                            if (StringHelper.hasAnyChar(detailNodes[5])) {
                                tmpRetDetail.askNumber = detailNodes[5].trim();
                            }
                            if ("借".equals(detailNodes[9])) {
                                tmpRetDetail.cdFlag = "27";
                                tmpRetDetail.billType = "1";
                            } else {
                                tmpRetDetail.cdFlag = "22";
                                tmpRetDetail.billType = "2";
                            }
                            if (StringHelper.hasAnyChar(detailNodes[3])) {
                                tmpRetDetail.amount = detailNodes[3].trim();
                            }
                            tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date8Format.parse(detailNodes[1]));
                            if (StringHelper.hasAnyChar(detailNodes[6])) {
                                tmpRetDetail.oppAct = detailNodes[6].trim();
                            }
                            tmpRetDetail.transState = TransState.Success;
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    }
                }
                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            } else {
                respHeader[0] = "0";
                respHeader[1] = "对账文件内容为空！";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }

    /**
     * 参考文档：中国银行银企对接接口规范V2.17（基础金融服务类交易）.pdf
     * 参考章节：2.44. 对账服务-对账单下载(b2e0359)
     *
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */
    public String[] getStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;
//        try {
//            BOC01Header bankHeader = new BOC01Header();
//            bankHeader.trncod = "b2e0359";//交易代码
//            bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
//            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
//            //写入通用的头部节点
//            //Date tmpDateNow = new Date();
//            writeCommonHeader(xmlWriter, bankHeader);
//            xmlWriter.writeStartElement("trn-" + bankHeader.trncod + "-rq");
//            xmlWriter.writeStartElement(bankHeader.trncod + "-rq");
//            xmlWriter.writeElementString("insid", p_reqQrySttm.askNumber);//客户业务编号
//            xmlWriter.writeElementString("stmtnum", p_reqQrySttm.statementNumber);//对账单号
//            xmlWriter.writeEndDocument();//写入报文完成
//
//            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
//            if (tmpStrRet[0].length() == 0) {
//                StringBuilder tmpSbMsg = new StringBuilder();
//                //解析银行返回
//                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
//                if (tmpBkReader != null) {
//                    String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspcod");
//                    String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/status/rspmsg");
//                    if (isActiveRetCode(tmprspcod)) {
//                        retAts.writeRespCode("0");
//                        while (tmpBkReader.read("/bocb2e/trans/trn-" + bankHeader.trncod + "-rs/" + bankHeader.trncod + "-rs")) {
//                            //文件名称规则：客户号_交易日期_交易类型_下载序号.gz，
//                            // 客户号指的是核心客户号，交易类型为CA+交易类型，下载序号从请求报文获取，交易日期格式为YYYYMMDD
//                            String downFileName = tmpBkReader.readedXElement.getSingleText("filename");
//
//
//                        }
//                    } else {
//                        retAts.writeRespCode("-1");
//                        retAts.writeRespInfo(tmprspmsg);
//                    }
//                } else {
//                    retAts.writeRespCode("-1");
//                    retAts.writeRespInfo(tmpStrRet[1]);
//                }
//            } else {
//                retAts.writeRespCode("-1");
//                retAts.writeRespInfo(tmpStrRet[1]);
//            }
//        } catch (Exception e) {
//            retAts.writeRespCode("-1");
//            retAts.writeRespInfo(e.getMessage());
//            e.printStackTrace();
//        }
        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }


}
